import axios from 'axios'
import { Toast } from 'vant'
import router from '@/router'
import {getItem, removeItem} from '@/utils'

axios.defaults = {
  withCredentials: true,
  headers: {
    token: localStorage.getItem('token') || ''
  }
}

axios.interceptors.request.use(req => {
  Toast.loading({
    duration: 0,
    forbidClick: true,
    message: '加载中...'
  })
  const token = getItem('token')
  req.headers['token'] = token
  return req
})

axios.interceptors.response.use(res => {
  Toast.clear()
  if (typeof res.data !== 'object') {
    Toast.fail('服务异常')
    return Promise.reject(res)
  }
  if (res.data.resultCode === 416) {
    router.push({ path: '/login' })
    removeItem('token')
  }
  if (res.data.resultCode !== 200) {
    Toast.fail(res.data.message || '数据异常')
    return res.data
  }
  return res.data
}, err => {
  Toast.clear()
  console.log(err)
  Toast.fail('请求失败')
})

export default axios
